package service

import (
	"duoke/model"
	"duoke/tables"
	"duoke/utils/orm"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
)

var CourseLecturer = new(courseLecturerService)

type courseLecturerService struct {
	TablesName string
}

func (s *courseLecturerService) Init() *courseLecturerService {
	s.TablesName = "course_lecturer"
	return s
}

// List 列表
func (s *courseLecturerService) List(c *gin.Context, req *model.ReqList) ([]map[string]interface{}, int64, error) {
	// 查询结果
	where := ""
	if req.Keyword != "" {
		where = fmt.Sprintf("name like '%s' or college like '%s'", "%"+req.Keyword+"%", "%"+req.Keyword+"%")
	}
	list, total, err := tableCommon.QueryListWithPage(c, "course_lecturer", where, req.PageNo,
		req.PageSize)
	if err != nil {
		return nil, 0, err
	}
	return list, total, nil
}

// Save 保存
func (s *courseLecturerService) Save(c *gin.Context, req *model.CourseLecturerTab) (int64, error) {
	accountR, _ := Request.Account(c)
	where := ""
	if req.Id > 0 {
		where = fmt.Sprintf("id=%d", req.Id)
	}
	req.Acid = accountR.Id
	var data int64
	var err error
	if req.Id > 0 {
		data, err = tableCommon.SaveData("course_lecturer", req, where, "update")
	} else {
		data, err = tableCommon.SaveData("course_lecturer", req, where, "insert")
	}
	if err != nil {
		return 0, err
	}
	return data, err
}

// Del 删除
func (s *courseLecturerService) Del(id int) (int64, error) {
	i, err := orm.Db.ID(id).Delete(&tables.CourseLecturer{})
	if err != nil {
		return 0, err
	}
	return i, nil
}

func (s *courseLecturerService) Info(id int) (*tables.CourseLecturer, error) {
	course_lecturer := new(tables.CourseLecturer)
	has, err := orm.Db.Where("id=?", id).Get(course_lecturer)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("该教师不存在")
	}

	return course_lecturer, nil
}
